#region Telligent Copyright Header

//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

#endregion

#region Import Declarations

using System.IO;
using System;
using System.Security;
using System.Collections;
using System.Xml;
using CommunityServer.Components;
using System.Collections.Generic;
using CommunityServer.Galleries.Components;
using CommunityServer.Galleries;

#endregion

namespace CommunityServerStuff.CSModules
{
    class AutoGalleryCreateInRoleGroup : ICSModule
    {

        #region Private Members

        private Hashtable roleMappings = new Hashtable();

        #endregion

        #region Methods

        #region Constructor

        public AutoGalleryCreateInRoleGroup()
        {
            EventLogs.Warn("AutoCreateGalleryInRoleGroup Module loaded", "Registration", 301);
        }

        #endregion

        #region Init

        public void Init(CSApplication csa, XmlNode node)
        {
            foreach (XmlNode childNode in node.ChildNodes)
            {
                if (childNode.Name == "RoleMapping")
                {
                    roleMappings.Add(childNode.Attributes["RoleName"].Value, int.Parse(childNode.Attributes["GroupId"].Value));
                }
            }
            csa.PostUserUpdate += new CSUserEventHandler(csa_PostUserUpdate);
        }

        #endregion

        #region csa_PostUserUpdate

        private void csa_PostUserUpdate(User user, CSEventArgs e)
        {
            try
            {
            if (user != null && e.State == ObjectState.Update)
            {
                if (user.GetExtendedAttribute("galleryAutoCreated").Equals(string.Empty) || bool.Parse(user.GetExtendedAttribute("galleryAutoCreated")))
                {
                    return;
                }

                GalleryConfiguration config = GalleryConfiguration.Instance();
                if (config.AutoCreateGallery)
                {
                    string formattedKey = null;
                    CSContext cSContext = CSContext.Current;
                    Globals.ValidateApplicationKey(user.Username, out formattedKey);

                    if (Globals.IsNullorEmpty(formattedKey) || Galleries.Exists(formattedKey))
                    {
                        return;
                    }

                    Gallery g = new Gallery();
                    g.ApplicationKey = formattedKey;

                    int groupid = config.DefaultGroupID;

                    foreach (string r in roleMappings.Keys)
                    {
                        if (System.Web.Security.Roles.IsUserInRole(user.Username, r))
                        {
                            groupid = (int)roleMappings[r];
                            EventLogs.Warn("RoleMapping found. Role: " + roleMappings[r].ToString(), "RoleGalleryCreate", 941);
                            break;
                        }
                    }

                    if (groupid <= 0)
                    {
                        EventLogs.Warn("If we found a RoleMapping we shouldn't be here.", "RoleGalleryCreate", 941);
                        List<Group> groups = GalleryGroups.GetGroups(true, false, false);
                        if (groups.Count > 0)
                            groupid = groups[0].GroupID;
                    }

                    if (groupid <= 0)
                        return;

                    EventLogs.Warn("Final Group: " + groupid, "RoleGalleryCreate", 941);

                    g.GroupID = groupid;
                    g.Name = user.Username;
                    g.IsActive = true;
                    g.SettingsID = cSContext.SiteSettings.SettingsID;
                    g.ApplicationType = ApplicationType.Gallery;
                    g.DateCreated = DateTime.Now;
                    g.Owners = user.Username;
                    g.IsSearchable = true;
                    g.EnableRss = true;

                    //Create The Gallery
                    g.SectionID = CommunityServer.Galleries.Galleries.AddGallery(g);

                    // Add the gallery url to the users profile
                    if (Globals.IsNullorEmpty(user.Profile.WebGallery))
                    {
                        user.Profile.WebGallery = Globals.FullPath(g.Url);
                        user.SetExtendedAttribute("galleryAutoCreated", "true");
                    }

                    //Create the Folder on the webserver
                    try
                    {
                        if (GalleryConfiguration.Instance().CreateGalleryDirectories)
                            WebDirectory.Create(Globals.GetSiteUrls().Locations["galleries"] + g.ApplicationKey);
                    }
                    catch (IOException ex)
                    { new CSException(CSExceptionType.AccessDenied, "CreateGallery: Permission to add the folder on filesystem denied.", ex).Log(); }
                    catch (SecurityException ex)
                    { new CSException(CSExceptionType.AccessDenied, "CreateGallery: Permission to add the folder on filesystem denied.", ex).Log(); }
                    catch { }

                    //Not Cluster safe, but lets try and update the cache
                    CommunityServer.Galleries.Galleries.GetGalleries(cSContext.User.UserID, true, true, true);
                }
            }
        }
        catch (Exception ex)
        {
            CSException csex = new CSException(CSExceptionType.UnknownError, null, ex);
            csex.Log(CSContext.Current.SettingsID);
        }
        }

        #endregion

        #endregion
    }
}
